import * as remote from '@electron/remote';
import { SimulateController } from './Controller';
import { ExportDialogOption, SaveDialogOption } from './types/localfile';
import { BrowserWindow } from "electron";
import { loading } from "@/common/Loading";

export default class LocalFileService {
  dialog: Electron.Dialog
  controller: SimulateController;

  constructor(c: SimulateController) {
    this.dialog = remote.dialog;
    this.controller = c;
  }

  showExportCSVDialog(option?: ExportDialogOption){
    return this.dialog.showSaveDialogSync(
      remote.getCurrentWindow(),
      option || {
        title: this.controller.locale.localeTrans('export'),
        filters: [{ name: this.controller.locale.localeTrans('ex_tables'), extensions: ['csv'] }]
      });
  }

  async writeDataToCSV(csvData: string, filePath: string) { loading.popup(this.controller.locale.localeTrans('_exporting'));
    setTimeout(() => {
      loading.close();
    }, 1200);
    await new Promise((resolve) => {
      window.$ele.fs.writeFile(filePath, csvData, (err) => {
        if (err) {
          console.error(err);
          return;
        }
        resolve(true);
      });
    });
  }

  async chooseSaveFilePath(option: SaveDialogOption) {
    let options:Electron.SaveDialogOptions = {
      properties: ['createDirectory'],
      ...option
    };
    const result = await remote.dialog.showSaveDialog(
      remote.BrowserWindow.getFocusedWindow() as BrowserWindow,
      options
    );
    return result;
  }

  async saveDataToCSV(data: string[][]) {
    const filePath = this.showExportCSVDialog();
    if (filePath) {
      await this.writeDataToCSV(data.map(lineinfos => lineinfos.join(',')).join('\n'), filePath);
    }
  }
}